package com.gitee.helioz.openai.common.util;

import com.gitee.helioz.openai.common.error.OpenAiRuntimeException;
import com.google.common.collect.Sets;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 〈Bean操作工具类〉
 *
 * @author <a href="https://gitee.com/helioz">Morning Starr</a>
 */
public class BeanUtil {

    public static Map<String, Object> beanToMap(Object bean, String... ignoreFields) {
        Set<String> ignoreFieldSet = Sets.newHashSet(ignoreFields);
        Class<?> clazz = bean.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Map<String, Object> formMap = new HashMap<>(fields.length);
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if (!ignoreFieldSet.contains(fieldName)) {
                try {
                    Object fieldValue = field.get(bean);
                    if (fieldValue != null) {
                        formMap.put(fieldName, fieldValue);
                    }
                } catch (IllegalAccessException e) {
                    throw new OpenAiRuntimeException(e);
                }
            }
        }
        return formMap;
    }

}
